package com.umeox.iqibla.custom_tasbih.receiver

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import com.umeox.iqibla.custom_tasbih.TaskDetail
import com.umeox.iqibla.custom_tasbih.Utils
import com.umeox.iqibla.custom_tasbih.ui.TriggerActivity
import com.umeox.moto.common.log.Logger
import com.umeox.moto.common.utils.DateUtils
import com.umeox.watch.moto.dataservice.constants.Constants


class TaskReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action
        if (action == null || TextUtils.isEmpty(action)) {
            return
        }

        if (action == Constants.ACTION_UPDATED_TASK_LIST) {
            Logger.w("任务列表更新，先取消设置的任务闹钟，然后重新计算")
            cancelAlarm(context)
            val taskDataList = Utils.getAlarmList()
            //获取下次闹钟时间，并且计算重复闹钟下次响铃时间
            val nextTask = Utils.getNextAlarmDetail(taskDataList)
            if (nextTask != null) {
                setAlarm(context, nextTask)
            } else {
                Logger.w("当前没有可用任务闹钟")
                cancelAlarm(context)
            }
        } else if (action == ACTION_TASK_BELL) {
            Logger.w("收到任务闹钟广播")
            val newIntent = Intent()
            newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            newIntent.setClass(context, TriggerActivity::class.java)
            context.startActivity(newIntent)
        }
    }

    @SuppressLint("WrongConstant")
    private fun setAlarm(context: Context, detail: TaskDetail) {
        val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager?
        if (am == null) {
            Logger.w( "The service named alarm does not exist.")
            return
        }
        val intent = Intent()
        intent.setAction(ACTION_TASK_BELL)
        val mBundle = Bundle()
        mBundle.putString(EXTRA_KEY_ID, "task")
        intent.putExtras(mBundle)
        val pdIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )

        val time = detail.alarmTimeInMillis
        val currentTime = System.currentTimeMillis()
        Logger.w("当前时间:" + DateUtils.formatDateTime(currentTime))
        Logger.w("任务闹钟时间:" + DateUtils.formatDateTime(time))
        //set方法4.4以后已经不能精确到设置的时间，改用setExact方法设置闹钟
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pdIntent)
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.RTC_WAKEUP, time, pdIntent)
        } else {
            am[AlarmManager.RTC_WAKEUP, time] = pdIntent
        }
    }

    /**
     * 1.   Intent中的setData使用的值，必须和cancel中intent里面setData用的值一样，否则点击cancel是没法取消掉的，
     * 或者你不setData，那也是没法取消的
     * 2.   Intent中的setClass使用的值也必须和cancel众intent使用的一样，不然也cancel不掉，不setClass也cancel不了
     * 3.   Intent中的putExtra是无效的，根本不起区别的作用
     * 4.   getBroadcast的第二个参数，一般的ap都是写0,其实假如你前面的intent只有setAction过，
     * 那么单纯用reqeustCode也是可以区别不同的alarm的。
     * 5.   通常cancel之前可以先用PendingIntent.FLAG_NO_CREATE来判断之前是不是设定了这个alarm，
     * 假如没设定，那就不要去调用cancel
     */
    private fun cancelAlarm(context: Context) {
        val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent()
        intent.setAction(ACTION_TASK_BELL)
        val mBundle = Bundle()
        mBundle.putString(EXTRA_KEY_ID, "task")
        intent.putExtras(mBundle)
        val sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_NO_CREATE)
        if (sender != null) {
            log("取消已经设置的任务闹钟")
            am.cancel(sender)
        } else {
            log("当前没有设置任务闹钟，不用取消")
        }
    }

    private fun log(text: String) {
        Logger.d(TAG, text)
    }

    companion object {
        private val TAG: String = TaskReceiver::class.java.simpleName
        private const val ACTION_TASK_BELL = "com.wherecom.intent.action.ACTION_TASK_BELL"
        private const val EXTRA_KEY_ID = "KEY"
    }
}


